<?php

namespace Project\Admin\Traits;

trait menu
{
    // 转成树形结构菜单
    public function menu_tree($pid = 0)
    {
        $data = \Project\Admin\Models\AdminMenu::all();
        return data_tree($data, $pid, 'parent_id');
    }

    // 找出对应 ID 的菜单
    public function menu_select($id)
    {
        return array_select($this->menu_tree(), 'id', $id, 'children');
    }

    // 角色组对应菜单
    public function menu_roles($role_ids)
    {
        $roles = \Project\Admin\Models\AdminRoleMenu::whereIn('id', $role_ids)->pluck('rules')->toArray();
        $rules = [];
        if ($roles) {
            foreach ($roles as $v) {
                $rules = array_merge($rules, explode(',', $v));
            }
            $rules = array_unique($rules);
        }
        if (in_array('*', $rules))
            return $this->menu_tree();

        $data = \Project\Admin\Models\AdminMenu::whereIn('id', $rules)->get();
        return data_tree($data, 0, 'parent_id');
    }

    /**
     * 找出菜单上级
     * 
     * @param integer $id
     */
    public function findTop(&$parent, $id, $level = 0)
    {
        $_menu = \Project\Admin\Models\AdminMenu::find($id);
        $parent[$level] = $_menu;
        if ($_menu->parent_id > 0)
            $this->findTop($parent, $_menu->parent_id, $level++);
    }
}
